import cv2
import numpy as np
import time
from flask import Flask

class face_detector():
    def __init__(self):
        self.eye_cascade=cv2.CascadeClassifier(cv2.data.haarcascades+"haarcascade_eye.xml")
        self.face_cascade=cv2.CascadeClassifier(cv2.data.haarcascades+"haarcascade_frontalface_default.xml")

    def countFace(self):
        cap = cv2.VideoCapture(0)
        ret,frame=cap.read()
        i=frame
        gray=cv2.cvtColor(i,cv2.COLOR_BGR2GRAY)
        faces=self.face_cascade.detectMultiScale(gray,1.3,5)
        return len(faces)

    def getFaces(self,ts=2):
        init = time.time()
        faces =[]
        while True:
            faces.append(self.countFace())
            if time.time() - init >ts:
                faces.sort(reverse=True)
                return faces[0]

app = Flask(__name__)
@app.route("/")
def service():
    fd = face_detector()
    results = fd.getFaces(2)
    return {"person":results}

if __name__ == "__main__":
    app.run('0.0.0.0')
